package com.example.xiongmao.handler;

import com.example.xiongmao.constant.MessageConstant;
import com.example.xiongmao.entity.Result;
import com.example.xiongmao.exception.AccountLockedException;
import com.example.xiongmao.exception.AccountNotFoundException;
import com.example.xiongmao.exception.BaseException;
import com.example.xiongmao.exception.PasswordErrorException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
//        log.error("异常信息：{}", ex.getMessage());
        System.out.println("异常信息：{}"+ex.getMessage());
        return Result.error(ex.getMessage());
    }
    /**
     * 用于捕获SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result doSQLException(SQLIntegrityConstraintViolationException ex) {
        // 使用正则提取更可靠
        Pattern pattern = Pattern.compile("Duplicate entry '(.*?)' for key '(.*?)'");
        Matcher matcher = pattern.matcher(ex.getMessage());

        if (matcher.find()) {
            String duplicateValue = matcher.group(1);
            String constraintName = matcher.group(2);

            String errorMessage = switch (constraintName) {
                case "username" -> duplicateValue + MessageConstant.USERNAME_ALREADY_EXIST;
                case "email" -> duplicateValue + MessageConstant.EMAIL_ALREADY_EXIST;
                case "phone_number" -> duplicateValue + MessageConstant.PHONENUMBER_ALREADY_EXIST;
                default -> MessageConstant.DUPLICATE_ENTRY;
            };
            return Result.error(errorMessage);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

    @ExceptionHandler(AccountNotFoundException.class)
    public Result<String> handleAccountNotFoundException(AccountNotFoundException e) {
        return Result.error("账号不存在");
    }

    @ExceptionHandler(PasswordErrorException.class)
    public Result<String> handlePasswordErrorException(PasswordErrorException e) {
        return Result.error("密码错误");
    }

    @ExceptionHandler(AccountLockedException.class)
    public Result<String> handleAccountLockedException(AccountLockedException e) {
        return Result.error("账号已被锁定");
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        return Result.error("系统异常: " + e.getMessage());
    }


}
